<html>

<head>
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
<div id="app">
</div>
<script>
const {
  createApp,
  defineComponent,
  setup,
  ref,
  onMounted,
  onUnmounted,
} = Vue;

function fetchLocation() {
  let positionWatcher;
  const geoLocation = navigator.geolocation;
  const gpsTime = ref(Date.now());
  const coordinates = ref({
    accuracy: 0,
    latitude: 0,
    longitude: 0,
    altitude: 0,
    altitudeAccuracy: 0,
    heading: 0,
    speed: 0,
  });

  function setPosition(payload) {
    gpsTime.value = payload.timestamp
    coordinates.value = payload.coords
  }

  onMounted(() => {
    if (geoLocation) positionWatcher = geoLocation.watchPosition(setPosition);
  });

  onUnmounted(() => {
    if (positionWatcher) geoLocation.clearWatch(positionWatcher);
  });

  return {
    coordinates,
    gpsTime,
  };
}

const appComponent = defineComponent({
  setup() {
    const {
      coordinates,
      gpsTime,
    } = fetchLocation();
    const formatOptions = {
      year: 'numeric',
      month: 'numeric',
      day: 'numeric',
      hour: 'numeric',
      minute: 'numeric',
      hour12: true,
    };

    const formatDate = (date) => (new Intl.DateTimeFormat(navigator.language, formatOptions).format(date));

    return {
      coordinates,
      gpsTime,
      formatDate
    };
  },
  template: `
    <h1>My Geo Position at {{formatDate(new Date(gpsTime))}}</h1>
    <ul>
      <li>Latitude: {{ coordinates.latitude }}</li>
      <li>Longitude: {{ coordinates.longitude }}</li>
      <li>Altitude: {{ coordinates.altitude  }}</li>
    </ul>
  `
});

createApp(appComponent)
  .mount('#app');
</script>
</body>

</html>
